#
from typing import Dict, List, Any
import os
import requests
import json
import numpy as np
from fastmcp import FastMCP
from fastmcp import Client # Import the client
import asyncio
from apps.cpm.mcp.mcpc_fm import McpcFm
from config.app_config import AppConfig as AC

class DrawXYsMcpcFm(object):
    client = Client('http://127.0.0.1:8000/mcp/')

    def __init__(self):
        self.name = 'apps.cpm.mcp.draw_x_ys_mcpc_fm.DrawXYsMcpcFm'
        

    @staticmethod
    def call_mcp_server(x:np.ndarray, ys:List) -> Dict:
        print(f'### x: {x.shape}, {x.dtype};')
        McpcFm.upload_obj('x', x)
        for i in range(len(ys)):
            print(f'    ys_{i}: {ys[0]['data'].shape}; {ys[0]['data'].dtype};')
            McpcFm.upload_obj(f'ys_{i}', ys[i]['data'])
        # Run the local test function
        result = asyncio.run(DrawXYsMcpcFm.test_server_locally(x, ys)).structured_content
        # Commented out for now, we'll focus on running the server next
        print(f'MCP调用结果：{type(result)}; {result};')
        return {'result': 0, 'params': {'img_fn': result['images'][0]['img_fn']}}

    @staticmethod
    async def test_server_locally(x:np.ndarray, ys:List):
        # Clients are asynchronous, so use an async context manager
        titles_raw, labels_raw = [], []
        for ysi in ys:
            titles_raw.append(ysi['title'])
            labels_raw.append(ysi['labels'])
        async with DrawXYsMcpcFm.client:
            result = await DrawXYsMcpcFm.client.call_tool('draw_x_ys', {'v_keys': 'x', 'vs_keys': f'ys:{len(ys)}', 'titles_raw': json.dumps(titles_raw), 'labels_raw': json.dumps(labels_raw)})
            # print(f'result: {type(result)}; \n{result.structured_content};')
        return result

if '__main__' == __name__:
    print(f'MCP客户端 v0.0.2')
    x = np.zeros((1000,), dtype=np.float32)
    ys = [np.zeros((3, 1000), dtype=np.float32), np.ones((3, 1000), dtype=np.float32)]
    mcp_result = DrawXYsMcpcFm.call_mcp_server(x, ys)
    print(f'mcp_result: {mcp_result};')

    # x[5] = 5.0
    # x[6] = 6.0
    # DrawXYsMcpcFm.upload_obj('x', x)
    # # DrawXYsMcpcFm.upload_obj('ys_0', ys[0])
    # # DrawXYsMcpcFm.upload_obj('ys_1', ys[1])
    # # # print(f'{type(x0)};')
    # x_raw = DrawXYsMcpcFm.get_key_obj('x')
    # print(f'size: {len(x_raw)}; {type(x_raw)};')
    # x0 = np.frombuffer(x_raw, dtype=np.float32)
    # print(f'x0: {x0.shape}; {x0[5]}; {x0[6]}; {x0[7]};')

    # z = x.tobytes()
    # print(f'z: {len(z)};')
    # x1 = np.frombuffer(z, dtype=np.float32)
    # print(f'x1: {x1.shape};')
    # img_fn = 'docs/images/d00/f00.png'
    # with open(img_fn, 'rb') as rfd:
    #     content = rfd.read()
    # result = McpcFm.upload_file('png', content)
    # print(f'url: {result["url"]};')
    # fn = 'fn_00000001.png'
    # content = McpcFm.download_file(fn)
    # with open(f'./work/{fn}', 'wb') as wfd:
    #     wfd.write(content)

